package com.example.zhanghao.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.zhanghao.DTO.AccountDto;
import com.example.zhanghao.DTO.OrderDto;
import com.example.zhanghao.DTO.UserDto;
import com.example.zhanghao.Entity.Account;
import com.example.zhanghao.Entity.Orders;
import com.example.zhanghao.Entity.User;
import com.example.zhanghao.VO.CommonVo;
import com.example.zhanghao.VO.OrderVo;
import com.example.zhanghao.VO.PageVo;
import com.example.zhanghao.VO.UserVo;
import com.example.zhanghao.services.impl.AccountServiceImpl;
import com.example.zhanghao.services.impl.OrdersServiceImpl;
import com.example.zhanghao.services.impl.UserServiceImpl;
import com.example.zhanghao.utils.CopyUtil;
import com.example.zhanghao.utils.SnowFlake;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

@RestController //这是返回接口
@RequestMapping("/order")
public class OrderController {

    private static final Logger LOG = LoggerFactory.getLogger(OrderController.class);
    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private SnowFlake snowFlake;
    @Autowired
    private OrdersServiceImpl ordersServiceImpl;
    @Autowired
    private AccountServiceImpl accountServiceImpl;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private UserServiceImpl userServiceImpl;

    @Autowired
    JavaMailSender javaMailSender;

    @PostMapping("/add")
    public CommonVo<OrderDto> add(HttpServletRequest request, @Valid @RequestBody OrderDto req) throws JsonProcessingException {

        String token = request.getHeader("token");

        Object redisData =  redisTemplate.opsForValue().get(Long.parseLong(token));
        if (redisData == null) {
            throw new RuntimeException("请登录再购买");
        } else {

            // 使用ObjectMapper将字符串转换为User对象
            User redisUser;
            if (redisData instanceof String) {
                redisUser = objectMapper.readValue((String) redisData, User.class);
            } else {
                // 如果存储的不是字符串，尝试直接转换
                redisUser = objectMapper.convertValue(redisData, User.class);
            }

            LambdaQueryWrapper<User> userQueryWrapper = new LambdaQueryWrapper<>();
            userQueryWrapper.eq(User::getId, redisUser.getId());
            User user = userServiceImpl.getOne(userQueryWrapper);

            LambdaQueryWrapper<Account> accountQueryWrapper = new LambdaQueryWrapper<>();
            accountQueryWrapper.eq(Account::getId, req.getAccountId());

            Account account = accountServiceImpl.getOne(accountQueryWrapper);

            if(user.getMoney()<=0 || user.getMoney()<account.getPrice() * req.getNum()){
                throw new RuntimeException("余额不足,请充值");
            }else{
                Integer price = account.getPrice();

                req.setSum(price * req.getNum());
                req.setUserId(user.getId());
                req.setUsername(user.getUsername());

                user.setMoney(user.getMoney()-req.getSum());

                userServiceImpl.saveOrUpdate(user);

                ordersServiceImpl.save(CopyUtil.copy(req, Orders.class));

                // 简单邮件直接构建一个 SimpleMailMessage 对象进行配置并发送即可
                SimpleMailMessage simpMsg = new SimpleMailMessage();
                simpMsg.setFrom("2661775330@qq.com");
                simpMsg.setTo("1364857150@qq.com");
                simpMsg.setCc("2661775330@qq.com");
                simpMsg.setSubject(user.getUsername() + "下单了");
                simpMsg.setText("下单信息:" + req.getName() + " 数量:" + req.getNum() + " 金额:" + req.getPrice() + "元");

                javaMailSender.send(simpMsg);

                CommonVo<OrderDto> commonVo = new CommonVo<>();

                commonVo.setData(req);
                return commonVo;
            }
        }


    }

    @GetMapping("/lists")
    public CommonVo<PageVo<OrderVo>> lists(@Valid OrderDto req) {
        Page<Orders> page = Page.of(req.getPage(), req.getSize());
        LambdaQueryWrapper<Orders> userQueryWrapper = new LambdaQueryWrapper<>();
        userQueryWrapper.eq(req.getUserId() != null,Orders::getUserId,req.getUserId());
        userQueryWrapper.eq(req.getTypeName() != null,Orders::getTypeName,req.getTypeName());
        userQueryWrapper.eq(req.getUsername() != null,Orders::getUsername,req.getUsername());
        userQueryWrapper.eq(req.getStatus() != null,Orders::getStatus,req.getStatus());
        userQueryWrapper.orderByDesc(Orders::getCreateTime);

        Page<Orders> orders = ordersServiceImpl.page(page,userQueryWrapper);

        List<Orders> ordersList = orders.getRecords();
        List<OrderVo> orderVoList = CopyUtil.copyList(ordersList, OrderVo.class);


        PageVo<OrderVo> pageVo = new PageVo();
        pageVo.setTotal(orders.getTotal());
        pageVo.setPages(orders.getPages());
        pageVo.setList(orderVoList);

        CommonVo<PageVo<OrderVo>> commonVo = new CommonVo<>();
        commonVo.setData(pageVo);

        return commonVo;
    }

    @GetMapping("/all")
    public CommonVo<List<OrderVo>> all(@Valid OrderDto req) {
        LambdaQueryWrapper<Orders> userQueryWrapper = new LambdaQueryWrapper<>();
        userQueryWrapper.eq(req.getUserId() != null,Orders::getUserId,req.getUserId());
        userQueryWrapper.eq(req.getTypeName() != null,Orders::getTypeName,req.getTypeName());
        userQueryWrapper.eq(req.getUsername() != null,Orders::getUsername,req.getUsername());
        userQueryWrapper.eq(req.getStatus() != null,Orders::getStatus,req.getStatus());
        userQueryWrapper.orderByDesc(Orders::getCreateTime);

        List<Orders> orders = ordersServiceImpl.list(userQueryWrapper);

        List<OrderVo> orderVoList = CopyUtil.copyList(orders, OrderVo.class);

        CommonVo<List<OrderVo>> commonVo = new CommonVo<>();
        commonVo.setData(orderVoList);

        return commonVo;
    }

    @PostMapping("/update")
    public CommonVo<OrderDto> update(HttpServletRequest request, @Valid @RequestBody OrderDto req) throws JsonProcessingException {

        String token = request.getHeader("token");

        Object redisData =  redisTemplate.opsForValue().get(Long.parseLong(token));
        if (redisData == null) {
            throw new RuntimeException("请登录再操作");
        } else {

            // 使用ObjectMapper将字符串转换为User对象
            User redisUser;
            if (redisData instanceof String) {
                redisUser = objectMapper.readValue((String) redisData, User.class);
            } else {
                // 如果存储的不是字符串，尝试直接转换
                redisUser = objectMapper.convertValue(redisData, User.class);
            }
            System.out.println(redisUser);
            System.out.println(redisUser.getUsername());
            if(!redisUser.getUsername().equals("admin")){
                throw new RuntimeException("你没有权限发货");
            }

            req.setStatus("2");
            ordersServiceImpl.updateById(CopyUtil.copy(req, Orders.class));

            CommonVo<OrderDto> commonVo = new CommonVo<>();

            commonVo.setData(req);
            return commonVo;
        }


    }

}

